<script setup>
import { ref, onMounted, computed, watch, onUnmounted } from 'vue';
import router from "@/router/index.js";
import { useRoute } from 'vue-router';
import { SERVER_BASE_URL } from "@/utils/request.js";
import request from '@/utils/request';
import categoryData from './category.json';
import { ElMessage } from 'element-plus';
import {ArrowRight, Search, Top} from '@element-plus/icons-vue';

const route = useRoute();
const activeTag = ref('');
const categoryList = ref(categoryData);
const selectedCategory = ref(null);
const commodities = ref([]);
const loading = ref(false);
const noMore = ref(false);
const searchKeyword = ref(''); // 搜索关键词

const queryParams = ref({
  pageNum: 1,
  pageSize: 12,
  name: '',
  status: 'ON_SALE', // 默认查询在售商品
  categoryTag: []
});

// 根据路由参数获取分类
const initFromRoute = () => {
  const { tag } = route.query;
  if (tag) {
    // 处理tag可能是字符串或数组的情况
    const tagArray = Array.isArray(tag) ? tag : [tag];
    activeTag.value = tagArray[0];
    
    // 查找匹配的分类
    const found = categoryList.value.find(item => {
      if (!item.Tag) return false;
      // 检查是否有任何一个标签匹配
      return item.Tag.some(t => tagArray.includes(t));
    });
    
    if (found) {
      selectedCategory.value = found;
      handleCategorySelect(found);
    }
  }
};

// 处理分类选择
const handleCategorySelect = (category) => {
  if (!category || !category.Tag || category.Tag.length === 0) return;
  
  // 重置查询状态，但保留搜索关键词
  queryParams.value.pageNum = 1;
  queryParams.value.categoryTag = category.Tag;
  noMore.value = false;
  commodities.value = [];
  selectedCategory.value = category;
  activeTag.value = category.Tag[0];
  
  // 更新URL，不触发路由变化
  const newQuery = { ...route.query, tag: category.Tag[0] };
  router.replace({ path: route.path, query: newQuery }, null, { shallow: true });
  
  // 加载数据
  fetchCommodities();
};

// 获取商品列表
const fetchCommodities = async () => {
  if (loading.value) return;
  loading.value = true;
  
  try {
    const params = new URLSearchParams();
    params.append('pageNum', queryParams.value.pageNum);
    params.append('pageSize', queryParams.value.pageSize);
    params.append('status', queryParams.value.status);
    
    // 添加商品名称查询参数
    if (queryParams.value.name && queryParams.value.name.trim() !== '') {
      params.append('name', queryParams.value.name.trim());
    }
    
    // 只有当categoryTag数组非空时才添加标签查询条件
    if (queryParams.value.categoryTag && queryParams.value.categoryTag.length > 0) {
      // 确保每个标签都作为单独的参数传递
      queryParams.value.categoryTag.forEach(tag => {
        params.append('categoryTag', tag);
      });
    }
    
    console.log('查询参数:', params.toString());
    const response = await request.get(`/commodities/page?${params.toString()}`);
    
    if (queryParams.value.pageNum === 1) {
      commodities.value = response.list || [];
    } else {
      commodities.value = [...commodities.value, ...(response.list || [])];
    }
    
    // 判断是否还有更多数据
    if (!response.list || commodities.value.length >= response.total) {
      noMore.value = true;
    }
  } catch (error) {
    ElMessage.error('获取商品列表失败');
    console.error(error);
  } finally {
    loading.value = false;
  }
};

// 加载更多
const loadMore = () => {
  if (loading.value || noMore.value) return;
  queryParams.value.pageNum++;
  fetchCommodities();
};

// 处理滚动事件
const handleScroll = () => {
  const scrollTop = document.documentElement.scrollTop || document.body.scrollTop;
  const clientHeight = document.documentElement.clientHeight;
  const scrollHeight = document.documentElement.scrollHeight;
  
  // 当滚动到距离底部100px时触发加载更多
  if (scrollHeight - scrollTop - clientHeight <= 100 && !loading.value && !noMore.value) {
    loadMore();
  }
};

// 跳转到商品详情
const goToDetail = (id) => {
  router.push(`/commodity/${id}`);
};

// 处理图片URL
const getImgUrl = (url) => {
  if (!url) return '';
  
  // 确保有服务器地址前缀
  const serverBaseUrl = SERVER_BASE_URL;
  let fullUrl = url;
  
  if (url.startsWith('/uploads/')) {
    fullUrl = serverBaseUrl + url;
  }
  
  return fullUrl;
};

// 监听路由变化
watch(() => route.query, (newQuery) => {
  if (newQuery.tag && newQuery.tag !== activeTag.value) {
    initFromRoute();
  }
}, { deep: true });

onMounted(() => {
  initFromRoute();
  // 如果没有从路由获取到分类，默认查询全部商品（不带Tag）
  if (!selectedCategory.value) {
    loadAllCommodities();
  }
  // 添加滚动事件监听
  window.addEventListener('scroll', handleScroll);
});

// 加载全部商品（不带Tag）
const loadAllCommodities = () => {
  // 重置查询状态，但保留搜索关键词
  queryParams.value.pageNum = 1;
  queryParams.value.categoryTag = []; // 设置为空数组
  noMore.value = false;
  commodities.value = [];
  selectedCategory.value = null;
  activeTag.value = '';
  
  // 更新URL，移除tag参数
  const newQuery = { ...route.query };
  delete newQuery.tag;
  router.replace({ path: route.path, query: newQuery }, null, { shallow: true });
  
  // 加载数据
  fetchCommodities();
};

// 组件卸载时移除事件监听
onUnmounted(() => {
  window.removeEventListener('scroll', handleScroll);
});

// 处理搜索事件
const handleSearch = () => {
  // 重置查询状态
  queryParams.value.pageNum = 1;
  queryParams.value.name = searchKeyword.value;
  noMore.value = false;
  commodities.value = [];
  
  // 加载数据
  fetchCommodities();
};

// 监听回车键触发搜索
const handleKeyUp = (event) => {
  if (event.key === 'Enter') {
    handleSearch();
  }
};

// 清除搜索
const clearSearch = () => {
  searchKeyword.value = '';
  queryParams.value.name = '';
  
  // 如果当前有选中分类，则重新加载分类商品
  if (selectedCategory.value) {
    handleCategorySelect(selectedCategory.value);
  } else {
    loadAllCommodities();
  }
};
</script>

<template>
  <div v-infinite-scroll="loadMore" class="category-view">
    <!-- 分类导航 -->
    <div class="category-nav">
      <div class="category-header">
        <h2>商品分类</h2>
        <!-- 搜索框 -->
        <div class="search-container">
          <el-input
            v-model="searchKeyword"
            placeholder="搜索商品名称或分类..."
            clearable
            @keyup="handleKeyUp"
            @clear="clearSearch"
          >
            <template #prefix>
              <el-icon><Search /></el-icon>
            </template>

          </el-input>
          <el-button type="primary" @click="handleSearch">搜索</el-button>
        </div>
      </div>
      
      <!-- 分类标签列表 -->
      <div class="category-tags">
        <!-- 全部商品选项 -->
        <el-tag 
          :type="selectedCategory === null ? 'primary' : 'info'"
          effect="light"
          class="category-tag-item"
          @click="loadAllCommodities"
        >
          全部分类
        </el-tag>
        <!-- 特定分类选项 -->
        <el-tag 
          v-for="category in categoryList" 
          :key="category.name"
          :type="selectedCategory && selectedCategory.name === category.name ? 'primary' : 'info'"
          effect="light"
          class="category-tag-item"
          @click="handleCategorySelect(category)"
        >
          {{ category.name }}
        </el-tag>
      </div>
    </div>
    
    <!-- 商品列表 -->
    <div class="commodity-container">
      <div v-if="commodities.length === 0 && !loading">
        <el-empty description="暂无商品数据" />
      </div>
      
      <div class="commodity-grid" v-else>
        <div
          v-for="item in commodities"
          :key="item.id"
          class="commodity-card"
          @click="goToDetail(item.id)"
        >
          <div class="commodity-image">
            <el-image
              :src="item.image && item.image.length > 0 ? getImgUrl(item.image[0]) : ''"
              fit="cover"
              lazy
            >
              <template #error>
                <div class="image-error">暂无图片</div>
              </template>
            </el-image>
            <div class="card-overlay">
              <span class="view-details">查看详情</span>
            </div>
          </div>
          <div class="commodity-info">
            <h3 class="commodity-name" :title="item.name">{{ item.name }}</h3>
            <div class="commodity-price">¥ {{ item.price }}</div>
            <div class="commodity-footer">
              <div class="commodity-sales">销量: {{ item.salesVolume || 0 }}</div>
              <div class="commodity-stock" v-if="item.stock">库存: {{ item.stock }}</div>
            </div>
          </div>
        </div>
      </div>
      
      <!-- 加载状态指示 -->
      <div class="loading-container" v-if="loading || noMore">
        <el-skeleton :loading="loading" animated :count="1" v-if="loading">
          <template #template>
            <div style="display:flex; justify-content:center; padding:20px;">
              <el-skeleton-item variant="p" style="width: 20%; height: 24px; margin: 0 auto;" />
            </div>
          </template>
        </el-skeleton>
        <p v-if="loading" class="loading-text">正在加载更多商品...</p>
        <p v-if="noMore && commodities.length > 0" class="no-more-text">已经到底啦~</p>
        <p v-if="noMore && commodities.length === 0" class="no-more-text">暂无商品数据</p>
      </div>
    </div>
  </div>

  <!-- 返回顶部按钮 -->
  <el-backtop :right="40" :bottom="40" :visibility-height="200" target=".el-main">
    <div class="back-top-box">
      <el-icon><Top /></el-icon>
    </div>
  </el-backtop>
</template>

<style scoped>
.category-view {
  width: 95%;
  margin: 20px auto;
  min-height: 500px;
}

.category-nav {
  margin-bottom: 20px;
  padding: 15px;
  background-color: white;
  border-radius: 8px;
  box-shadow: 0 2px 12px rgba(0, 0, 0, 0.05);
}

.category-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 20px;
}

.category-header h2 {
  font-size: 20px;
  color: #303133;
  margin: 0;
  flex-shrink: 0;
  margin-right: 15px;
}

.search-container {
  flex-grow: 1;
  max-width: 600px;
  display: flex;
  align-items: center;
}

.search-container .el-input {
  flex: 1;
  margin-right: 10px;
  box-shadow: 0 0 0 1px rgba(0, 0, 0, 0.06);
  border-radius: 4px;
  transition: all 0.3s;
}

.search-container .el-input:hover {
  box-shadow: 0 0 0 1px #409EFF;
}

.search-container .el-button {
  flex-shrink: 0;

}

.search-container .el-input__wrapper {
  box-shadow: none !important;
}

.search-container .el-input__inner {
  height: 40px;
  padding-left: 12px;
}

.category-tags {
  display: flex;
  flex-wrap: wrap;
  gap: 10px;
  margin-bottom: 15px;
}

.category-tag-item {
  cursor: pointer;
  padding: 8px 16px;
  font-size: 14px;
  transition: all 0.3s;
}

.category-tag-item:hover {
  transform: translateY(-2px);
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);
}

/* 响应式布局调整 */
@media (max-width: 768px) {
  .category-header {
    flex-direction: column;
    align-items: stretch;
  }
  
  .category-header h2 {
    margin-bottom: 15px;
    text-align: center;
  }
  
  .search-container {
    max-width: 100%;
    width: 100%;
  }
  
  .search-container .el-input {
    width: calc(100% - 80px);
  }
  
  .search-container .el-button {
    min-width: 70px;
  }
  
  .category-tags {
    justify-content: center;
  }
}

/* 商品容器样式 */
.commodity-container {
  width: 100%;
  height: 600px;
  border: none;
}

.commodity-grid {
  display: grid;
  grid-template-columns: repeat(auto-fill, minmax(220px, 1fr));
  gap: 20px;
  margin-bottom: 20px;
}

@media (max-width: 768px) {
  .commodity-grid {
    grid-template-columns: repeat(auto-fill, minmax(160px, 1fr));
    gap: 15px;
  }
}

.commodity-card {
  border-radius: 8px;
  overflow: hidden;
  transition: all 0.3s cubic-bezier(0.175, 0.885, 0.32, 1.275);
  cursor: pointer;
  box-shadow: 0 2px 10px rgba(0, 0, 0, 0.08);
  background-color: #fff;
  border: 1px solid #EBEEF5;
}

.commodity-card:hover {
  transform: translateY(-5px);
  box-shadow: 0 8px 20px rgba(0, 0, 0, 0.1);
}

.commodity-card:hover .card-overlay {
  opacity: 1;
}

.commodity-image {
  height: 250px;
  position: relative;
  overflow: hidden;
}

.el-image {
  width: 100%;
  height: 100%;
  object-fit: cover;
  transition: transform 0.5s ease;
}

.commodity-card:hover .el-image {
  transform: scale(1.05);
}

.card-overlay {
  position: absolute;
  top: 0;
  left: 0;
  width: 100%;
  height: 100%;
  background-color: rgba(0, 0, 0, 0.3);
  display: flex;
  align-items: center;
  justify-content: center;
  opacity: 0;
  transition: opacity 0.3s ease;
}

.view-details {
  color: white;
  font-size: 14px;
  font-weight: 500;
  padding: 6px 14px;
  border-radius: 20px;
  background-color: rgba(64, 158, 255, 0.8);
}

.image-error {
  height: 100%;
  display: flex;
  align-items: center;
  justify-content: center;
  background-color: #f5f7fa;
  color: #909399;
}

.commodity-info {
  padding: 12px;
}

.commodity-name {
  font-size: 14px;
  margin: 0 0 8px 0;
  overflow: hidden;
  text-overflow: ellipsis;
  white-space: nowrap;
  color: #303133;
  font-weight: 500;
}

.commodity-price {
  font-size: 16px;
  color: #ff6700;
  font-weight: bold;
  margin-bottom: 5px;
}

.commodity-footer {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.commodity-sales, .commodity-stock {
  font-size: 12px;
  color: #909399;
}

.loading-container {
  text-align: center;
  padding: 20px 0;
}

.loading-text {
  color: #409EFF;
  font-size: 14px;
  margin-top: 8px;
}

.no-more-text {
  color: #909399;
  font-size: 14px;
  margin-top: 8px;
  position: relative;
  display: inline-block;
  padding: 0 20px;
}

.no-more-text::before,
.no-more-text::after {
  content: '';
  position: absolute;
  top: 50%;
  width: 50px;
  height: 1px;
  background-color: #EBEEF5;
}

.no-more-text::before {
  left: -40px;
}

.no-more-text::after {
  right: -40px;
}

.back-top-box {
  width: 40px;
  height: 40px;
  background-color: #409EFF;
  display: flex;
  align-items: center;
  justify-content: center;
  color: white;
  border-radius: 50%;
  box-shadow: 0 2px 12px rgba(0, 0, 0, 0.2);
  transition: all 0.3s;
}

.back-top-box:hover {
  background-color: #66b1ff;
  transform: scale(1.1);
}
</style>